<template>
  <a_page :有工具栏="false">
    <div class="row flex-center">
      <q-card class="column flex-center  fit  q-gutter-lg">
        <SelectImage v-model="userStore.userInfo.avatar" file-type="image" />
        <div v-if="!editFlag">
          {{ userStore.userInfo.nick_name }}
          <q-btn dense color="primary" icon="edit" label="改昵称" @click="openEdit" />
        </div>
        <template v-if="editFlag">
          <div class="row">
            <el-input v-model="nick_name" />
          </div>
          <div class="row">
            <q-btn dense flat round color="primary" icon="check" @click="enterEdit" />
            <q-btn dense flat round color="negative" icon="clear" @click="closeEdit" />
          </div>
        </template>
        <q-list bordered separator class="fit">
          <q-item clickable v-ripple>
            <q-item-section avatar>
              <q-icon color="primary" name="person" />
            </q-item-section>
            <q-item-section>
              用户名:{{ userStore.userInfo.user_name }}
            </q-item-section>
          </q-item>
          <q-item clickable v-ripple>
            <q-item-section avatar>
              <q-icon color="primary" name="smartphone" />
            </q-item-section>
            <q-item-section>
              手机:{{ userStore.userInfo.mobile }}
            </q-item-section>
          </q-item>
          <q-item clickable v-ripple>
            <q-item-section avatar>
              <q-icon color="primary" name="lock" />
            </q-item-section>
            <q-item-section>
              <q-btn dense flat icon="edit" label="修改密码" @click="showPassword = true" />
            </q-item-section>
          </q-item>
        </q-list>
      </q-card>

    </div>
    <el-dialog v-model="showPassword" title="修改密码" width="360px" @close="clearPassword">
      <el-form ref="modifyPwdForm" :model="pwdModify" :rules="rules" label-width="80px">
        <el-form-item :minlength="6" label="原密码" prop="password">
          <el-input v-model="pwdModify.password" show-password />
        </el-form-item>
        <el-form-item :minlength="6" label="新密码" prop="newPassword">
          <el-input v-model="pwdModify.newPassword" show-password />
        </el-form-item>
        <el-form-item :minlength="6" label="确认密码" prop="confirmPassword">
          <el-input v-model="pwdModify.confirmPassword" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPassword = false">取 消</el-button>
          <el-button type="primary" @click="savePassword">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="changePhoneFlag" title="绑定手机" width="600px">
      <el-form :model="phoneForm">
        <el-form-item label="手机号" label-width="120px">
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号" autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" label-width="120px">
          <div class="flex w-full gap-4">
            <el-input v-model="phoneForm.code" class="flex-1" autocomplete="off" placeholder="请自行设计短信服务，此处为模拟随便写"
              style="width:300px" />
            <el-button type="primary" :disabled="time > 0" @click="getCode">{{ time > 0 ? `(${time}s)后重新获取` : '获取验证码'
            }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeChangePhone">取消</el-button>
          <el-button type="primary" @click="changePhone">更改</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="changeEmailFlag" title="绑定邮箱" width="600px">
      <el-form :model="emailForm">
        <el-form-item label="邮箱" label-width="120px">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱" autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" label-width="120px">
          <div class="flex w-full gap-4">
            <el-input v-model="emailForm.code" class="flex-1" placeholder="请自行设计邮件服务，此处为模拟随便写" autocomplete="off"
              style="width:300px" />
            <el-button type="primary" :disabled="emailTime > 0" @click="getEmailCode">{{
              emailTime > 0 ? `(${emailTime}s)后重新获取` : '获取验证码' }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeChangeEmail">取消</el-button>
          <el-button type="primary" @click="changeEmail">更改</el-button>
        </span>
      </template>
    </el-dialog>
  </a_page>
</template>

<script setup>
import { setSelfInfo, changePassword } from "amtf/api/user"
import { reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/use_user_store'
import SelectImage from '@/components/selectImage/selectImage.vue'

defineOptions({
  name: 'Person',
})

const activeName = ref('second')
const rules = reactive({
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, message: '最少6个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdModify.value.newPassword) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

const userStore = useUserStore()
const modifyPwdForm = ref(null)
const showPassword = ref(false)
const pwdModify = ref({})
const nick_name = ref('')
const editFlag = ref(false)
const savePassword = async () => {
  modifyPwdForm.value.validate((valid) => {
    if (valid) {
      changePassword({
        password: pwdModify.value.password,
        newPassword: pwdModify.value.newPassword,
      }).then((res) => {
        if (res.code === 0) {
          ElMessage.success('修改密码成功！')
        }
        showPassword.value = false
      })
    } else {
      return false
    }
  })
}

const clearPassword = () => {
  pwdModify.value = {
    password: '',
    newPassword: '',
    confirmPassword: '',
  }
  modifyPwdForm.value.clearValidate()
}

watch(() => userStore.userInfo.avatar, async (val) => {
  const res = await setSelfInfo({ avatar: val })
  if (res.code === 0) {
    userStore.ResetUserInfo({ avatar: val })
    ElMessage({
      type: 'success',
      message: '设置成功',
    })
  }
})

const openEdit = () => {
  nick_name.value = userStore.userInfo.nick_name
  editFlag.value = true
}

const closeEdit = () => {
  nick_name.value = ''
  editFlag.value = false
}

const enterEdit = async () => {
  const res = await setSelfInfo({
    nick_name: nick_name.value
  })
  if (res.code === 0) {
    userStore.ResetUserInfo({ nick_name: nick_name.value })
    ElMessage({
      type: 'success',
      message: '设置成功',
    })
  }
  nick_name.value = ''
  editFlag.value = false
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

const changePhoneFlag = ref(false)
const time = ref(0)
const phoneForm = reactive({
  phone: '',
  code: ''
})

const getCode = async () => {
  time.value = 60
  let timer = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

const closeChangePhone = () => {
  changePhoneFlag.value = false
  phoneForm.phone = ''
  phoneForm.code = ''
}

const changePhone = async () => {
  const res = await setSelfInfo({ phone: phoneForm.phone })
  if (res.code === 0) {
    ElMessage.success('修改成功')
    userStore.ResetUserInfo({ phone: phoneForm.phone })
    closeChangePhone()
  }
}

const changeEmailFlag = ref(false)
const emailTime = ref(0)
const emailForm = reactive({
  email: '',
  code: ''
})

const getEmailCode = async () => {
  emailTime.value = 60
  let timer = setInterval(() => {
    emailTime.value--
    if (emailTime.value <= 0) {
      clearInterval(timer)
      timer = null
    }
  }, 1000)
}

const closeChangeEmail = () => {
  changeEmailFlag.value = false
  emailForm.email = ''
  emailForm.code = ''
}

const changeEmail = async () => {
  const res = await setSelfInfo({ email: emailForm.email })
  if (res.code === 0) {
    ElMessage.success('修改成功')
    userStore.ResetUserInfo({ email: emailForm.email })
    closeChangeEmail()
  }
}

</script>
